import { H3Event } from 'h3'
import { query } from './mysql'

export interface LogOptions {
  authority?: string
  message?: string
  userId?: number
  username?: string
}

export async function recordLog(event: H3Event, opts: LogOptions = {}) {
  try {
    const req = (event as any).node && (event as any).node.req
    const res = (event as any).node && (event as any).node.res
    const method = (req && req.method) || ''
    // 抽取 path（某些运行时可能在 req.url，或 event.path）
    const path = (req && (req.url || req.originalUrl)) || (event as any).path || ''
    const status_code = (res && res.statusCode) || 0

    const authority = opts.authority ?? null
    let message = opts.message ?? null
    if (message && typeof message === 'string' && message.length > 500) message = message.slice(0, 500)
    const user_id = typeof opts.userId === 'number' ? opts.userId : 0
    const username = opts.username ?? null
    const create_time = new Date()

    const sql = `INSERT INTO lin_log (authority, message, method, path, status_code, user_id, username, create_time)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
    await query(sql, [authority, message, method, path, status_code, user_id, username, create_time])
  } catch (e) {
    // 记录日志失败不要影响主流程；尽量静默处理
    try { console.warn && console.warn('[recordLog] failed', e) } catch (ee) { /* ignore */ }
  }
}

export default { recordLog }
